<template>
  <a-input type="email" 
    :defaultValue="option.defaultValue" 
    placeholder="请填写邮箱地址" 
    @change="handleChange"></a-input>
</template>

<script>
import debounce from 'lodash/debounce'
const emailReg = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
export default {
  name: 'Email',
  props: {
    fieldId: {
      type: String,
      required: true
    },
    option: {
      type: Object,
      required: false,
      default: () => {
        return {
          showMask: true,
          maxLength: 100,
          defaultValue: undefined
        };
      }
    },
    defaultHelp: {
      type: String,
      required: false,
      default: () => {
        return '';
      }
    }
  },
  methods: {
    handleChange(e) {
      this.setValue(this, e.target.value);
    },
    setValue: debounce((self, value) => {
      if (value && !emailReg.test(value)) {
        self.$store.dispatch('validate', {fieldId: self.fieldId, status: 'error', help: '邮箱格式有误'});
      } else {
        self.$store.dispatch('validate', {fieldId: self.fieldId, status: undefined, help: self.defaultHelp});
        self.$emit('change', value);
      }
    }, 500)
  }
}
</script>

<style scoped>

</style>